package top.zywork.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import top.zywork.annotation.AppAuthFilter;
import top.zywork.common.ImageUtils;
import top.zywork.enums.ClientAppEnum;
import top.zywork.enums.ContentTypeEnum;
import top.zywork.enums.MIMETypeEnum;
import top.zywork.enums.SysConfigEnum;
import top.zywork.service.SysConfigService;
import top.zywork.vo.ResponseStatusVO;
import top.zywork.weixin.WeixinQrcodeUtils;
import top.zywork.weixin.WeixinUtils;
import top.zywork.weixin.WeixinXcxConfig;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;

/**
 * <p>微信小程序码控制器</p>
 * 创建于2019-07-19<br/>
 *
 * @author 王振宇
 * @version 1.0
 */
@RestController
@RequestMapping("/wx-qrcode")
@Slf4j
@AppAuthFilter(ignoreUrls = {
        "/wx-qrcode/unlimited"
})
public class WeixinQrcodeController extends BaseController {

    private SysConfigService sysConfigService;

    private RedisTemplate<String, Object> redisTemplate;

    @GetMapping("unlimited")
    public ResponseStatusVO getUnlimitedQrcode(String path, String scene, HttpServletResponse response) {
        WeixinXcxConfig weixinXcxConfig = sysConfigService.getByName(SysConfigEnum.WEIXIN_XCX_CONFIG.getValue(), WeixinXcxConfig.class);
        String accessToken = WeixinUtils.getAccessToken(redisTemplate, weixinXcxConfig.getAppId(), weixinXcxConfig.getAppSecret(), ClientAppEnum.WEIXIN_XCX);
        byte[] imgData = WeixinQrcodeUtils.getDefaultUnlimitedQrcode(accessToken, path, scene);
        if (imgData == null) {
            return ResponseStatusVO.error("未能生成小程序码", null);
        }
        BufferedImage bufferedImage = ImageUtils.getBufferedImage(imgData);
        if (bufferedImage != null) {
            response.setContentType(ContentTypeEnum.PNG.getValue());
            try {
                OutputStream outputStream = response.getOutputStream();
                ImageIO.write(bufferedImage, MIMETypeEnum.PNG.getValue(), outputStream);
                outputStream.close();
            } catch (IOException e) {
                log.error("get unlimited qrcode error： {}", e.getMessage());
            }
        }
        return null;
    }

    @Autowired
    public void setSysConfigService(SysConfigService sysConfigService) {
        this.sysConfigService = sysConfigService;
    }

    @Autowired
    public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }
}
